package com.nio;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetSocketAddress;

/**
 * @description
 * @author: wangtao
 * @date:17:05 2018/12/20
 * @email:taow02@jumei.com
 */
public class EchoServer {
	private final int port;

	public EchoServer(int port) {
		this.port = port;
	}

	public static void main(String[] args) throws Exception {
		if (args.length != 1) {
			args = new String[]{"23456"};
		}
		int port = Integer.parseInt(args[0]); //1
		new EchoServer(port).start(); //2
	}

	public void start() throws Exception {
		NioEventLoopGroup group = new NioEventLoopGroup(); //3
		NioEventLoopGroup worker = new NioEventLoopGroup(); //3
		try {
			ServerBootstrap b = new ServerBootstrap();
			b.group(group,worker) //4
					.channel(NioServerSocketChannel.class) //5
					.option(ChannelOption.SO_BACKLOG, 128)
					//有数据立即发送
					.option(ChannelOption.TCP_NODELAY, true)
					.childOption(ChannelOption.SO_KEEPALIVE, true)
					.localAddress(new InetSocketAddress(port)) //6
					.childHandler(new ChannelInitializer<SocketChannel>() { //7
						@Override
						public void initChannel(SocketChannel ch) throws Exception {
							ch.pipeline().addLast(new EchoServerHandler());
						}
					});
			ChannelFuture f = b.bind().sync(); //8
			System.out.println(EchoServer.class.getName() + " started and listen on " + f.channel().localAddress());
			f.channel().closeFuture().sync(); //9
		} finally {
			group.shutdownGracefully().sync(); //10
		}
	}
}